package com.nciae.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nciae.po.Teacher;
import com.nciae.dao.TeacherMapper;
import com.nciae.po.User;
import com.nciae.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nciae.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Guoliyu
 * @since 2022-03-30
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {

    @Autowired
    private IUserService userService;

    @Override
    public List<Teacher> findAll(String username) {
        List<Teacher> teachers = new ArrayList<>();
        List<User> users = userService.findUserByUsername(username);
        for(User user:users) {
            Teacher teacher = baseMapper.selectById(user.getId());
            if (!Objects.isNull(teacher)) {
                teacher.setUser(user);
                teachers.add(teacher);
            }
        }
        return teachers;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Teacher teacher) {
        String userJson = teacher.getUserJson();
        User user = (User) JSONObject.parse(userJson);
        if(!Objects.isNull(user)) {
            userService.add(user);
        }
        teacher.setId(user.getId());
        baseMapper.insert(teacher);
    }

    @Override
    public void update(Teacher teacher) {
        String userJson = teacher.getUserJson();
        User user = (User) JSONObject.parse(userJson);
        if(!Objects.isNull(user)) {
            user.setId(teacher.getId());
            userService.update(user);
        }
        baseMapper.updateById(teacher);
    }

    @Override
    public void delete(Long id) {
        userService.delete(id);
        baseMapper.deleteById(id);
    }

    @Override
    public Teacher findTeacherById(Long id) {
        return baseMapper.selectById(id);
    }
}
